<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />

    

    
    <title>深入分析前端小数计算问题 | 李世奇的技术专栏</title>
    
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
        <meta name="keywords" content="JavaScript" />
    
    <meta name="description" content="话不多说，先上代码function judgeFloat(n, m) &amp;#123;  const binaryN = n.toString(2);  const binaryM = m.toString(2);  console.log(`$&amp;#123;n&amp;#125;的二进制是    $&amp;#123;binaryN&amp;#125;`);  console.log(`$&amp;#123;m&amp;#125;的二进制">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="深入分析前端小数计算问题">
<meta property="og:url" content="https://www.lisq.xyz/2019/03/06/【JavaScript】深入分析前端小数计算问题/index.html">
<meta property="og:site_name" content="李世奇的技术专栏">
<meta property="og:description" content="话不多说，先上代码function judgeFloat(n, m) &amp;#123;  const binaryN = n.toString(2);  const binaryM = m.toString(2);  console.log(`$&amp;#123;n&amp;#125;的二进制是    $&amp;#123;binaryN&amp;#125;`);  console.log(`$&amp;#123;m&amp;#125;的二进制">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://www.lisq.xyz/img/4.jpg">
<meta property="og:updated_time" content="2019-04-06T05:28:05.940Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="深入分析前端小数计算问题">
<meta name="twitter:description" content="话不多说，先上代码function judgeFloat(n, m) &amp;#123;  const binaryN = n.toString(2);  const binaryM = m.toString(2);  console.log(`$&amp;#123;n&amp;#125;的二进制是    $&amp;#123;binaryN&amp;#125;`);  console.log(`$&amp;#123;m&amp;#125;的二进制">
<meta name="twitter:image" content="https://www.lisq.xyz/img/4.jpg">
    

    

    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/titillium-web/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    


</head>


<body>
    <div id="wrap">
        <header id="header">
    <div id="header-outer" class="outer">
        <div class="container">
            <div class="container-inner">
                <div id="header-title">
                    <h1 class="logo-wrap">
                        <a href="/" class="logo"></a>
                    </h1>
                    
                </div>
                <div id="header-inner" class="nav-container">
                    <a id="main-nav-toggle" class="nav-icon fa fa-bars"></a>
                    <div class="nav-container-inner">
                        <ul id="main-nav">
                            
                                <li class="main-nav-list-item" >
                                    <a class="main-nav-list-link" href="/">主页</a>
                                </li>
                            
                                        
                                    
                                <li class="main-nav-list-item" >
                                    <a class="main-nav-list-link" href="https://mp.weixin.qq.com/s/dYZEHTgqvxGV7mL99JuxRQ">关于</a>
                                </li>
                            
                                <li class="main-nav-list-item" >
                                    <a class="main-nav-list-link" href="https://github.com/ConardLi/ConardLi.github.io">更新日志</a>
                                </li>
                            
                                <li class="main-nav-list-item" >
                                    <a class="main-nav-list-link" href="/me/navigation.html">index.导航</a>
                                </li>
                            
                        </ul>
                        <nav id="sub-nav">
                            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>
        <div class="container">
            <div class="main-body container-inner">
                <div class="main-body-inner">
                    <section id="main">
                        <div class="main-body-header">
    <h1 class="header">
    
    未分类
    </h1>
</div>

                        <div class="main-body-content">
                            <style>
    #article-toc.fixed {
        position: fixed;
        top: 30px;
        bottom: 30px;
        left: 32px;
        padding-top: 15px;
        z-index: 9999;
        background-color: antiquewhite;
        width: 200px;
        padding-left: 20px;
        padding-bottom: 30px;
        border-radius: 10px;
        border: 1px solid rgb(122, 122, 122);
        opacity: 0.8;
    }

    #article-toc-inner {
        padding: 10px;
        width: 200px;
        height: 100%;
        overflow: auto;
    }

    .toc-level-3 {
        margin-left: 20px;
    }

    #article-toc a {
        text-decoration: none;
        color: #333;
        padding: 3px 0;
        color: #000;
        font-weight: normal;
    }

    .toc-item {
        line-height: 30px;
        list-style-type: initial;
    }

    #tocbtn {
        position: fixed;
        top: 30%;
        left: 0px;
        padding: 5px 2px;
        width: 18px;
        word-wrap: break-word;
        background-color: rgb(242, 245, 247);
        box-shadow: rgba(118, 118, 118, 0.11) 2px 0px 5px 0px;
        opacity: 1;
        height: 94px;
        line-height: 16px;
        text-align: center;
        top: 33%;
        width: 30px;
        z-index: 1000000001;
        cursor: pointer;
        border-radius: 0px 4px 4px 0px;
        border-width: 1px 1px 1px;
        border-style: solid solid solid none;
        border-color: rgb(224, 228, 231) rgb(224, 228, 231) rgb(224, 228, 231);
        border-image: initial;
        border-left: none;
        padding: 6px;
        transition: right 0.4s ease-in 0.3s, opacity 0.5s ease-in 0.3s;
    }
</style>

<article id="post-【JavaScript】深入分析前端小数计算问题"
    class="article article-single article-type-post"
    itemscope itemprop="blogPost">
    <div class="article-inner">
        
        <header class="article-header">
            
    
        <h1 class="article-title" itemprop="name">
        深入分析前端小数计算问题
        </h1>
    

        </header>
        
        
        <div class="article-meta">
            
    <div class="article-date">
        <a href="/2019/03/06/【JavaScript】深入分析前端小数计算问题/" class="article-date">
            <time datetime="2019-03-06T08:22:51.000Z" itemprop="datePublished">2019-03-06</time>
        </a>
    </div>

            

            
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/JavaScript/">JavaScript</a>
    </div>

            <span id="busuanzi_container_page_pv" style="position: relative;float: right;">
                本文总阅读量<span id="busuanzi_value_page_pv"></span>次
            </span>
        </div>
        
        
        <div class="article-entry" itemprop="articleBody">
            <p><img src="/img/4.jpg" alt="image"></p>
<h1 id="话不多说，先上代码"><a href="#话不多说，先上代码" class="headerlink" title="话不多说，先上代码"></a>话不多说，先上代码</h1><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">judgeFloat</span>(<span class="params">n, m</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> binaryN = n.toString(<span class="number">2</span>);</span><br><span class="line">  <span class="keyword">const</span> binaryM = m.toString(<span class="number">2</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;n&#125;</span>的二进制是    <span class="subst">$&#123;binaryN&#125;</span>`</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;m&#125;</span>的二进制是    <span class="subst">$&#123;binaryM&#125;</span>`</span>);</span><br><span class="line">  <span class="keyword">const</span> MN = m + n;</span><br><span class="line">  <span class="keyword">const</span> accuracyMN = (m * <span class="number">100</span> + n * <span class="number">100</span>) / <span class="number">100</span>;</span><br><span class="line">  <span class="keyword">const</span> binaryMN = MN.toString(<span class="number">2</span>);</span><br><span class="line">  <span class="keyword">const</span> accuracyBinaryMN = accuracyMN.toString(<span class="number">2</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;n&#125;</span>+<span class="subst">$&#123;m&#125;</span>的二进制是<span class="subst">$&#123;binaryMN&#125;</span>`</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;accuracyMN&#125;</span>的二进制是    <span class="subst">$&#123;accuracyBinaryMN&#125;</span>`</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;n&#125;</span>+<span class="subst">$&#123;m&#125;</span>的二进制再转成十进制是<span class="subst">$&#123;to10(binaryMN)&#125;</span>`</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;accuracyMN&#125;</span>的二进制是再转成十进制是<span class="subst">$&#123;to10(accuracyBinaryMN)&#125;</span>`</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;n&#125;</span>+<span class="subst">$&#123;m&#125;</span>在js中计算是<span class="subst">$&#123;(to10(binaryMN) === to10(accuracyBinaryMN)) ? <span class="string">''</span> : <span class="string">'不'</span>&#125;</span>准确的`</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">to10</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> pre = (n.split(<span class="string">'.'</span>)[<span class="number">0</span>] - <span class="number">0</span>).toString(<span class="number">2</span>);</span><br><span class="line">  <span class="keyword">const</span> arr = n.split(<span class="string">'.'</span>)[<span class="number">1</span>].split(<span class="string">''</span>);</span><br><span class="line">  <span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">let</span> result = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">while</span> (i &lt; arr.length) &#123;</span><br><span class="line">    result += arr[i] * <span class="built_in">Math</span>.pow(<span class="number">2</span>, -(i + <span class="number">1</span>));</span><br><span class="line">    i++;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line">judgeFloat(<span class="number">0.1</span>, <span class="number">0.2</span>);</span><br><span class="line">judgeFloat(<span class="number">0.6</span>, <span class="number">0.7</span>);</span><br></pre></td></tr></table></figure>
<p>由于<code>JavaScript</code>中没有将小数的<code>二进制</code>转换成<code>十进制</code>的方法，于是手动实现了一个。</p>
<p><img src="https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/blog/二进制3.png" alt="image"></p>
<h1 id="先来一个简单的结论"><a href="#先来一个简单的结论" class="headerlink" title="先来一个简单的结论"></a>先来一个简单的结论</h1><p>计算机中所有的数据都是以<code>二进制</code>存储的，所以在计算时计算机要把数据先转换成<code>二进制</code>进行计算，然后在把计算结果转换成<code>十进制</code>。</p>
<p>由上面的代码不难看出，在计算<code>0.1+0.2</code>时，<code>二进制</code>计算发生了精度丢失，导致再转换成<code>十进制</code>后和预计的结果不符。</p>
<p>其实有些标题党了，一个函数并不能让你深入理解，还得继续看下面…</p>
<h1 id="对结果的分析—更多的问题"><a href="#对结果的分析—更多的问题" class="headerlink" title="对结果的分析—更多的问题"></a>对结果的分析—更多的问题</h1><p><code>0.1</code>和<code>0.2</code>的二进制都是以1100无限循环的小数，下面逐个来看JS帮我们计算所得的结果：</p>
<p><strong>0.1的二进制</strong>：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">0.0001100110011001100110011001100110011001100110011001101</span><br></pre></td></tr></table></figure>
<p><strong>0.2的二进制</strong>：<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">0.001100110011001100110011001100110011001100110011001101</span><br></pre></td></tr></table></figure></p>
<p><strong>理论上讲，由上面的结果相加应该：</strong>：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">0.0100110011001100110011001100110011001100110011001100111</span><br></pre></td></tr></table></figure>
<p><strong>实际JS计算得到的0.1+0.2的二进制</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">0.0100110011001100110011001100110011001100110011001101</span><br></pre></td></tr></table></figure>
<p>作为一个代码强迫症的我又产生的新的问题：</p>
<blockquote>
<p>Why js计算出的 0.1的二进制 是这么多位而不是更多位？？？</p>
</blockquote>
<blockquote>
<p>Why js计算的（0.1+0.2）的二进制和我们自己计算的（0.1+0.2）的二进制结果不一样呢？？？</p>
</blockquote>
<blockquote>
<p>Why 0.1的二进制 + 0.2的二进制 != 0.3的二进制？？？</p>
</blockquote>
<h1 id="js对二进制小数的存储方式"><a href="#js对二进制小数的存储方式" class="headerlink" title="js对二进制小数的存储方式"></a>js对二进制小数的存储方式</h1><p>小数的<code>二进制</code>大多数都是无限循环的，<code>JavaScript</code>是怎么来存储他们的呢？</p>
<p>在<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.19" target="_blank" rel="noopener">ECMAScript®语言规范</a>中可以看到，<code>ECMAScript</code>中的<code>Number</code>类型遵循<code>IEEE 754</code>标准。使用64位固定长度来表示。</p>
<p>事实上有很多语言的数字类型都遵循这个标准，例如<code>JAVA</code>,所以很多语言同样有着上面同样的问题。</p>
<p>所以下次遇到这种问题不要上来就喷<code>JavaScript</code>…</p>
<p>有兴趣可以看看下这个网站<a href="http://0.30000000000000004.com/" target="_blank" rel="noopener">http://0.30000000000000004.com/</a>，是的，你没看错，就是<a href="http://0.30000000000000004.com/" target="_blank" rel="noopener">http://0.30000000000000004.com/</a>！！！</p>
<h1 id="IEEE-754"><a href="#IEEE-754" class="headerlink" title="IEEE 754"></a>IEEE 754</h1><p>IEEE754标准包含一组实数的二进制表示法。它有三部分组成：</p>
<ul>
<li><p>符号位</p>
</li>
<li><p>指数位</p>
</li>
<li><p>尾数位</p>
</li>
</ul>
<p>三种精度的浮点数各个部分位数如下：</p>
<p><img src="https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/blog/二进制1.png" alt="image"></p>
<p><code>JavaScript</code>使用的是64位双精度浮点数编码，所以它的<code>符号位</code>占<code>1</code>位，指数位占<code>11</code>位，尾数位占<code>52</code>位。</p>
<p>下面我们在理解下什么是<code>符号位</code>、<code>指数位</code>、<code>尾数位</code>，以<code>0.1</code>为例：</p>
<p>它的二进制为：<code>0.0001100110011001100...</code></p>
<p>为了节省存储空间，在计算机中它是以科学计数法表示的，也就是</p>
<p><code>1.100110011001100...</code> X 2<sup>-4</sup></p>
<p>如果这里不好理解可以想一下十进制的数：</p>
<p><code>1100</code>的科学计数法为<code>11</code> X 10<sup>2</sup></p>
<p>所以：</p>
<p><img src="https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/blog/二进制2.png" alt="image"></p>
<p><code>符号位</code>就是标识正负的，<code>1</code>表示<code>负</code>，<code>0</code>表示<code>正</code>；</p>
<p><code>指数位</code>存储科学计数法的指数；</p>
<p><code>尾数位</code>存储科学计数法后的有效数字；</p>
<p>所以我们通常看到的二进制，其实是计算机实际存储的尾数位。</p>
<h1 id="js中的toString-2"><a href="#js中的toString-2" class="headerlink" title="js中的toString(2)"></a>js中的toString(2)</h1><p>由于尾数位只能存储<code>52</code>个数字，这就能解释<code>toString(2)</code>的执行结果了：</p>
<p>如果计算机没有存储空间的限制，那么<code>0.1</code>的<code>二进制</code>应该是：<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">0.00011001100110011001100110011001100110011001100110011001...</span><br></pre></td></tr></table></figure></p>
<p>科学计数法尾数位</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">1.1001100110011001100110011001100110011001100110011001...</span><br></pre></td></tr></table></figure>
<p>但是由于限制，有效数字第<code>53</code>位及以后的数字是不能存储的，它遵循，如果是<code>1</code>就向前一位进<code>1</code>，如果是<code>0</code>就舍弃的原则。</p>
<p>0.1的二进制科学计数法第53位是1，所以就有了下面的结果：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">0.0001100110011001100110011001100110011001100110011001101</span><br></pre></td></tr></table></figure>
<p><code>0.2</code>有着同样的问题，其实正是由于这样的存储，在这里有了精度丢失，导致了<code>0.1+0.2!=0.3</code>。</p>
<p>事实上有着同样精度问题的计算还有很多，我们无法把他们都记下来，所以当程序中有数字计算时，我们最好用工具库来帮助我们解决，下面是两个推荐使用的开源库：</p>
<ul>
<li><p><a href="https://github.com/nefe/number-precision" target="_blank" rel="noopener">number-precision</a></p>
</li>
<li><p><a href="https://github.com/josdejong/mathjs/" target="_blank" rel="noopener">mathjs/</a></p>
</li>
</ul>
<p>下面我们再来看上面的其他两个问题。</p>
<h1 id="Why-JavaScript计算出的-0-1的二进制-是这么多位而不是更多位？？？"><a href="#Why-JavaScript计算出的-0-1的二进制-是这么多位而不是更多位？？？" class="headerlink" title="Why JavaScript计算出的 0.1的二进制 是这么多位而不是更多位？？？"></a>Why JavaScript计算出的 0.1的二进制 是这么多位而不是更多位？？？</h1><p>上面的<code>toString</code>原理帮我们解答了这个问题，在有效数字第<code>53</code>位以后的数字将遵循<code>1进0舍</code>的原则，内存中只允许存储<code>52</code>位有效数字。</p>
<h1 id="Why-JavaScript计算的（0-1-0-2）的二进制和我们自己计算的（0-1-0-2）的二进制结果不一样呢？？？"><a href="#Why-JavaScript计算的（0-1-0-2）的二进制和我们自己计算的（0-1-0-2）的二进制结果不一样呢？？？" class="headerlink" title="Why JavaScript计算的（0.1+0.2）的二进制和我们自己计算的（0.1+0.2）的二进制结果不一样呢？？？"></a>Why JavaScript计算的（0.1+0.2）的二进制和我们自己计算的（0.1+0.2）的二进制结果不一样呢？？？</h1><p><strong>我们自己计算的0.1+0.2：</strong>：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">0.0100110011001100110011001100110011001100110011001100111</span><br></pre></td></tr></table></figure>
<p>实际上这个结果的有效数字已经超过了<code>52</code>位，我们要从末尾进行<code>1进0舍</code>得到下面的结果</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">0.0100110011001100110011001100110011001100110011001101</span><br></pre></td></tr></table></figure>
<h1 id="JavaScript能表示的最大数字"><a href="#JavaScript能表示的最大数字" class="headerlink" title="JavaScript能表示的最大数字"></a>JavaScript能表示的最大数字</h1><p>由与<code>IEEE 754</code>双精度64位规范的限制：</p>
<p><code>指数位</code>能表示的最大数字：<code>1023</code>(十进制)</p>
<p><code>尾数位</code>能表达的最大数字即尾数位都位<code>1</code>的情况</p>
<p>所以JavaScript能表示的最大数字即位</p>
<p><code>1.111...</code>X 2<sup>1023</sup> 这个结果转换成十进制是<code>1.7976931348623157e+308</code>,这个结果即为<code>Number.MAX_VALUE</code>。</p>
<h1 id="最大安全数字"><a href="#最大安全数字" class="headerlink" title="最大安全数字"></a>最大安全数字</h1><p>JavaScript中<code>Number.MAX_SAFE_INTEGER</code>表示最大安全数字,计算结果是<code>9007199254740991</code>，即在这个数范围内不会出现精度丢失（小数除外）,这个数实际上是<code>1.111...</code>X 2<sup>52</sup>。</p>
<p>我们同样可以用一些开源库来处理大整数：</p>
<ul>
<li><a href="https://github.com/justmoon/node-bignum" target="_blank" rel="noopener">node-bignum</a></li>
<li><a href="https://github.com/substack/node-bigint" target="_blank" rel="noopener">node-bigint</a></li>
</ul>
<p>其实官方也考虑到了这个问题，<code>bigInt</code>类型在<code>es10</code>中被提出，现在<code>Chrome</code>中已经可以使用。</p>
<h1 id="bigInt类型"><a href="#bigInt类型" class="headerlink" title="bigInt类型"></a>bigInt类型</h1><p><code>BigInt</code> 是第七种原始类型。</p>
<p><code>BigInt</code> 是一个任意精度的整数。这意味着变量现在可以计算<code>9007199254740991</code>即最大安全整数以上的数字。</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const b = 1n;  // 追加 n 以创建 BigInt</span><br></pre></td></tr></table></figure>
<p>在过去，不支持大于 <code>9007199254740992</code> 的整数值。如果超过，该值将锁定为<code>MAX_SAFE_INTEGER + 1</code>:</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">const limit = Number.MAX_SAFE_INTEGER;</span><br><span class="line">⇨ 9007199254740991</span><br><span class="line">limit + 1;</span><br><span class="line">⇨ 9007199254740992</span><br><span class="line">limit + 2;</span><br><span class="line">⇨ 9007199254740992 &lt;--- MAX_SAFE_INTEGER + 1 exceeded</span><br><span class="line">const larger = 9007199254740991n;</span><br><span class="line">⇨ 9007199254740991n</span><br><span class="line">const integer = BigInt(9007199254740991); // initialize with number</span><br><span class="line">⇨ 9007199254740991n</span><br><span class="line">const same = BigInt(&quot;9007199254740991&quot;); // initialize with &quot;string&quot;</span><br><span class="line">⇨ 9007199254740991n</span><br></pre></td></tr></table></figure>
<p>typeof<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">typeof 10;</span><br><span class="line">⇨ &apos;number&apos;</span><br><span class="line">typeof 10n;</span><br><span class="line">⇨ &apos;bigint&apos;</span><br></pre></td></tr></table></figure></p>

        </div>
        <footer class="article-footer">
            



    <a data-url="https://www.lisq.xyz/2019/03/06/【JavaScript】深入分析前端小数计算问题/" data-id="cjv0hxjy00000nh0det04t38w" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

        </footer>
    </div>
</article>


    <section id="comments">
    
        
    <div id="disqus_thread">
        <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>

    
    </section>





<div id="roott"></div>

<button id="tocbtn">打开目录</button>


<script>
    var showToc = false;
    document.getElementById('tocbtn').onclick = function () {
        if (showToc) {
            document.getElementById('roott').innerHTML = ''
            document.getElementById('tocbtn').innerHTML = '打开目录'
        } else {
            document.getElementById('roott').innerHTML = `<aside id="article-toc" role="navigation" class="fixed">
  <div id="article-toc-inner">
    <strong class="sidebar-title">
      目录</strong>
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#话不多说，先上代码"><span class="toc-text">话不多说，先上代码</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#先来一个简单的结论"><span class="toc-text">先来一个简单的结论</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#对结果的分析—更多的问题"><span class="toc-text">对结果的分析—更多的问题</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#js对二进制小数的存储方式"><span class="toc-text">js对二进制小数的存储方式</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#IEEE-754"><span class="toc-text">IEEE 754</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#js中的toString-2"><span class="toc-text">js中的toString(2)</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Why-JavaScript计算出的-0-1的二进制-是这么多位而不是更多位？？？"><span class="toc-text">Why JavaScript计算出的 0.1的二进制 是这么多位而不是更多位？？？</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Why-JavaScript计算的（0-1-0-2）的二进制和我们自己计算的（0-1-0-2）的二进制结果不一样呢？？？"><span class="toc-text">Why JavaScript计算的（0.1+0.2）的二进制和我们自己计算的（0.1+0.2）的二进制结果不一样呢？？？</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript能表示的最大数字"><span class="toc-text">JavaScript能表示的最大数字</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#最大安全数字"><span class="toc-text">最大安全数字</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#bigInt类型"><span class="toc-text">bigInt类型</span></a></li></ol>
  </div>
</aside>`
            document.getElementById('tocbtn').innerHTML = '关闭目录'
        }
        showToc = !showToc;
    }
</script>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
<div id="vcomments" style="padding: 30px;"></div>
<script>
    new Valine({
        el: '#vcomments',
        appId: 's1xL54gwvPRsIy3ciItiPhyD-gzGzoHsz',
        appKey: 'CmP8stKpHUHtp5abbTxpqc4H'
    })
</script>
                        </div>
                    </section>
                    <aside id="sidebar">
    <a class="sidebar-toggle" title="Expand Sidebar"><i class="toggle icon"></i></a>
    <div class="sidebar-top">
        <p>
            关注我 :</p>
        <ul class="social-links">
            
            
            <li>
                <a class="social-tooltip" title="github" href="https://github.com/ConardLi"
                    target="_blank" rel="noopener">
                    <i class="icon fa fa-github"></i>
                </a>
            </li>
            
            
        </ul>
    </div>
    
    
<nav id="article-nav">
    
        <a href="/2019/03/12/【前端工程】前端开发者必备的nginx知识/" id="article-nav-newer" class="article-nav-link-wrap">
        <strong class="article-nav-caption">下一篇</strong>
        <p class="article-nav-title">
        
            前端开发者必备的nginx知识
        
        </p>
        <i class="icon fa fa-chevron-right" id="icon-chevron-right"></i>
    </a>
    
    
        <a href="/2019/03/06/【React深入】React事件机制/" id="article-nav-older" class="article-nav-link-wrap">
        <strong class="article-nav-caption">上一篇</strong>
        <p class="article-nav-title">【React深入】React事件机制</p>
        <i class="icon fa fa-chevron-left" id="icon-chevron-left"></i>
        </a>
    
</nav>

    
    <div class="widgets-container" style="background-color: #fff; border-right: 1px solid #e2e2e2;">
        
        
        
<div class="widget-wrap widget-list">
    <h3 class="widget-title">
        微信公众号
    </h3>
    <div class="widget">
        <img src="https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/gzh/qrcode.jpg" alt="">
    </div>
</div>

        
        

        
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="">
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/04/26/【自检】前端知识清单/" class="thumbnail">
    
    
        <span style="background-image:url(https://lsqimg-1257917459.cos.ap-beijing.myqcloud.com/blog/知识体系.png)" alt="【自检】前端知识清单" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/04/26/【自检】前端知识清单/" class="title">【自检】前端知识清单</a></p>
                            <p class="item-date"><time datetime="2019-04-26T01:11:22.000Z" itemprop="datePublished">2019-04-26</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/04/17/【React深入】深入分析虚拟DOM的渲染原理和特性/" class="thumbnail">
    
    
        <span style="background-image:url(https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/blog/react11.png)" alt="【React深入】深入分析虚拟DOM的渲染原理和特性" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/04/17/【React深入】深入分析虚拟DOM的渲染原理和特性/" class="title">【React深入】深入分析虚拟DOM的渲染原理和特性</a></p>
                            <p class="item-date"><time datetime="2019-04-17T03:15:27.000Z" itemprop="datePublished">2019-04-17</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/04/09/【React深入】从Mixin到HOC再到Hook/" class="thumbnail">
    
    
        <span style="background-image:url(https://lsqimg-1257917459.cos-website.ap-beijing.myqcloud.com/blog/hoc9.png)" alt="【React深入】从Mixin到HOC再到Hook" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/04/09/【React深入】从Mixin到HOC再到Hook/" class="title">【React深入】从Mixin到HOC再到Hook</a></p>
                            <p class="item-date"><time datetime="2019-04-09T15:27:27.000Z" itemprop="datePublished">2019-04-09</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/03/28/【浏览器和网络】全面分析前端的网络请求方式/" class="thumbnail">
    
    
        <span style="background-image:url(/img/network.jpg)" alt="全面分析前端的网络请求方式" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/03/28/【浏览器和网络】全面分析前端的网络请求方式/" class="title">全面分析前端的网络请求方式</a></p>
                            <p class="item-date"><time datetime="2019-03-28T12:38:59.000Z" itemprop="datePublished">2019-03-28</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2019/03/12/【前端工程】前端开发者必备的nginx知识/" class="thumbnail">
    
    
        <span style="background-image:url(/img/nginx.jpg)" alt="前端开发者必备的nginx知识" class="thumbnail-image"></span>
    
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"></p>
                            <p class="item-title"><a href="/2019/03/12/【前端工程】前端开发者必备的nginx知识/" class="title">前端开发者必备的nginx知识</a></p>
                            <p class="item-date"><time datetime="2019-03-12T06:50:35.000Z" itemprop="datePublished">2019-03-12</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

        
        
<div class="widget-wrap widget-list">
    <div class="">
        <h3 class="widget-title">标签</h3>
        <div class="widget widget-wrap-inn">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/学习提升/">-学习提升</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript/">JavaScript</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/React/">React</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/electron/">electron</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nginx/">nginx</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/博客搭建/">博客搭建</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/性能优化/">性能优化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/浏览器和网络/">浏览器和网络</a><span class="tag-list-count">1</span></li></ul>
        </div>
    </div>
</div>


<style>
    .widget-wrap-inn {
        background-color: white;
        padding: 10px;
        border-radius: 5px;
        border: 1px solid #ddd;
    }
</style>
        
        
<div class="widget-wrap widget-list">
    <h3 class="widget-title">归档</h3>
    <div class="widget  widget-wrap-inn">
        <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/04/">四月 2019</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/03/">三月 2019</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/12/">十二月 2018</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/11/">十一月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">1</span></li></ul>
    </div>
</div>

        
        
<div class="widget-wrap widget-list">
    <h3 class="widget-title">友情链接</h3>
    <div class="widget  widget-wrap-inn">
        <ul>
            
            <li>
                <a href="https://juejin.im/user/5bea27965188250edf4ad8b7">掘金</a>
            </li>
            
            <li>
                <a href="https://segmentfault.com/u/conardli">segmentfault</a>
            </li>
            
            <li>
                <a href="https://github.com/ConardLi">github</a>
            </li>
            
            <li>
                <a href="https://github.com/ConardLi/tpanorama">tpanorama</a>
            </li>
            
            <li>
                <a href="http://chuangzaoshi.com/">创造狮导航</a>
            </li>
            
        </ul>
    </div>
</div>

        
        
<div class="widget-wrap widget-list">
    <!-- <h3 class="widget-title">
        腾讯云专属福利
    </h3> -->
    <div class="widget">
        <a target="_blank"
            href="https://cloud.tencent.com/redirect.php?redirect=1025&cps_key=1a3e7b07487819e129852ba7a4543262&from=console">
            <img src="/img/txy.jpg" id="txy" alt="">
        </a>
    </div>
</div>



<style>
    #txy {
        width: 280px;
        border: 5px;
    }
</style>
        
        
<div class="widget-wrap widget-list">
    <div class="widget">
        <a target="_blank" href="https://promotion.aliyun.com/ntms/act/qwbk.html?userCode=y3kv7eoj">
            <img src="/img/aly.png" id="txy" alt="">
        </a>
    </div>
</div>



<style>
    #txy {
        width: 280px;
        border: 5px;
    }
</style>
        
        
    </div>
</aside>
                </div>
            </div>
        </div>
        <footer id="footer">
    <div class="container">
        <div class="container-inner">
            <a id="back-to-top" href="javascript:;"><i class="icon fa fa-angle-up"></i></a>
            <div class="credit">
                <h1 class="logo-wrap">
                    <a href="/" class="logo"></a>
                </h1>
                <p>&copy;
                    2019
                    ConardLi
                </p>
                <p>Powered by <a href="//hexo.io/" target="_blank">Hexo</a>. Theme by <a href="//github.com/ppoffice"
                        target="_blank">ConardLi</a></p>
                <script type="text/javascript">
                    var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");
                    document.write(unescape("%3Cspan id='cnzz_stat_icon_1275088352'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s22.cnzz.com/z_stat.php%3Fid%3D1275088352%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));
                </script>
                <span id="busuanzi_container_site_pv" style="margin-left:50px;">
                    本站总访问量<span id="busuanzi_value_site_pv"></span>次
                </span>
                <span id="busuanzi_container_site_uv" style="margin-left:50px;">
                    本站访客数<span id="busuanzi_value_site_uv"></span>人次
                </span>
            </div>
            <div class="footer-plugins">
                
    


            </div>
        </div>
    </div>
</footer>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
        
    
    <script>
    var disqus_shortname = 'hexo-theme-hueman';
    
    
    var disqus_url = 'https://www.lisq.xyz/2019/03/06/【JavaScript】深入分析前端小数计算问题/';
    
    (function() {
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
    </script>




    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>

</html>